package vmcs.factory;

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

import vmcs.entity.Coin;
import vmcs.entity.DrinksBrand;
import vmcs.entity.StoreObject;

public class ObjectRegistry {

	private static Map<CloneableObjectEnum, Cloneable> objectRegistry=new HashMap<CloneableObjectEnum, Cloneable>();
	
	public static Object lookup(CloneableObjectEnum objecType)  {
		
		Object storeObject=null;
		
		try {
			Cloneable cloneableObject=null;
			
				cloneableObject =(Cloneable)objectRegistry.get(objecType);
				
				if (cloneableObject==null){
					
					cloneableObject = constructObject(objecType);
					
					objectRegistry.put(objecType, cloneableObject);
					
					
				}
			
				Object clone = clone(cloneableObject);
				return clone;
				
		} catch (Exception e) {
			System.err.println("Error cloning object");
			e.printStackTrace();
		}
		return storeObject;
		
	}

	private static Cloneable constructObject( CloneableObjectEnum objecType) {
		
		Cloneable cloneableObjectImpl=null;
		
		switch(objecType){
								
			case COIN:
				cloneableObjectImpl=new Coin();
				break;
				
			case DRINK:
				cloneableObjectImpl=new DrinksBrand();
				break;
		}
		
		if (cloneableObjectImpl==null){
			//should ideally throw exception. this comes in when the enum value is passed as null
			System.err.println("Object Implementation could not be resolved. Please check your object type and object mapping");
		}
		
		return cloneableObjectImpl;
	}
	
	
	private static Object clone(Cloneable cloneableObject) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException, CloneNotSupportedException {
		
		//return cloneableObject.getClass().getMethod("clone").invoke(cloneableObject);
		//if this is just going to be a storeObject now
		return ((StoreObject)cloneableObject).clone();
	}
}
